package org.goodprinciples.commons.dao;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author iksyos
 */
public abstract class AbstractDAOFactory {

    private static Map<String, AbstractDAOFactory> instanceMap = new HashMap<>();
    
    public static <T extends AbstractDAOFactory> T getFactoryInstance(Class<T> factory) {
        try {
            if(!instanceMap.containsKey(factory.getName())) {
                instanceMap.put(factory.getName(), (T) factory.newInstance());
            }
            return (T) instanceMap.get(factory.getName());
        } catch(InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("can't create DAOFactory "+factory);
        }
    }

    protected <T> T instantiateDAO(Class<? extends GenericDAO> dao) {
        try {
            return (T) dao.newInstance();
        } catch(InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("can't create DAO "+dao, e);
        }
    }

}
